using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
using WeFeTeLib;

namespace WeFeTeUI
{
    public partial class frmMain : Form
    {
        System.Reflection.Assembly thisExe = System.Reflection.Assembly.GetExecutingAssembly();
		
		public delegate void ParameterizedThreadStart (object obj);

        public frmMain()
        {
            InitializeComponent();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            cbFramework.DataSource = Enum.GetValues(typeof(FrameworkFactory.FrameworkType));
        }

        private void btnCheck_Click(object sender, EventArgs e)
        {
            CleanDebug();
            
            // Initialization of DataGridView
            dgvResults.Columns.Clear();
            dgvResults.Columns.Add("icon", "");
            dgvResults.Columns.Add("name", "Framework");
            dgvResults.Columns["name"].CellTemplate = new DataGridViewTextBoxCell();
            dgvResults.Columns.Add("value", "Percent");
            dgvResults.Columns["value"].CellTemplate = new DataGridViewTextBoxCell();
			

            if (cbCheckAll.Checked)
            {
                CheckAll();
            }
            else
            {
				Thread t = new Thread(CheckOne);
				t.Start((FrameworkFactory.FrameworkType)cbFramework.SelectedItem);
            }
        }

        private void CheckOne(object frameworkType)
        {
			FrameworkFactory.FrameworkType type = (FrameworkFactory.FrameworkType)frameworkType;
            tssText.Text = "Processing " + type.ToString();
            tspProgress.Visible = true;
            tspProgress.Value = 0;

            FrameworkTester tester = new FrameworkTester(tbURL.Text, type);

            tester.OnTestFinished += new FrameworkTester.OnTestFinishedDelegated(tester_OnTestFinished);
            tester.OnPartCompleted += new FrameworkTester.OnPartCompletedDelegated(tester_OnPartCompleted);

            tester.Start();
        }

        void tester_OnPartCompleted(int amount)
        {
			if(tspProgress.Value + amount <= 100)
            	tspProgress.Value += amount;
        }

        private void CheckAll()
        {
            foreach (FrameworkFactory.FrameworkType frameworkType in cbFramework.Items)
            {
				Thread t = new Thread(CheckOne);
				t.Start(frameworkType);
            }
        }

        void tester_OnTestFinished(string FrameworkName, int Percent, List<Result> results)
        {
            // Debug information
            foreach (Result result in results)
            {
                WriteToDebug("The " + result.ResourceType + " " + result.ResourceName +
                    " match " + result.Conditions + " conditions\r\n");
            }

            WriteToDebug("The page " + tbURL.Text + " match " 
                + Percent + "% against the " + FrameworkName + " framework\r\n");

            WriteToDebug("-------------------------------------------------\r\n");


            // Datagridview
            #region Framework Header
            DataGridViewRow frameworkRow = new DataGridViewRow();
            DataGridViewTextBoxCell frameworkName = new DataGridViewTextBoxCell();
            DataGridViewImageCell imageResult = new DataGridViewImageCell();
            DataGridViewTextBoxCell percentResult = new DataGridViewTextBoxCell();
            frameworkName.Value = FrameworkName;
            percentResult.Value = Percent.ToString() + "%";
            imageResult.Description = "Framework";

            if(Percent == 0)
                imageResult.Value = Image.FromStream(
                    thisExe.GetManifestResourceStream("WeFeTeUI.icons.status-offline.png"));
            else if(Percent > 0 && Percent <= 20)
                imageResult.Value = Image.FromStream(
                    thisExe.GetManifestResourceStream("WeFeTeUI.icons.status-busy.png"));
            else if(Percent > 20 && Percent < 50)
                imageResult.Value = Image.FromStream(
                    thisExe.GetManifestResourceStream("WeFeTeUI.icons.status-away.png"));
            else
                imageResult.Value = Image.FromStream(
                    thisExe.GetManifestResourceStream("WeFeTeUI.icons.status.png"));

            frameworkRow.Cells.Add(imageResult);
            frameworkRow.Cells.Add(frameworkName);
            frameworkRow.Cells.Add(percentResult);
            DataGridViewCellStyle style = new DataGridViewCellStyle();
            style.BackColor = Color.LightGray;
            style.Alignment = DataGridViewContentAlignment.MiddleCenter;
            frameworkRow.DefaultCellStyle = style;
            dgvResults.Rows.Add(frameworkRow);
            #endregion

            #region Results cells
            foreach (Result result in results)
            {
                DataGridViewRow row = new DataGridViewRow();
                DataGridViewImageCell icon = new DataGridViewImageCell();
                DataGridViewTextBoxCell name = new DataGridViewTextBoxCell();
                
                icon.Description = result.ResourceType;

                switch (result.ResourceType)
                {
                    case "File":
                        if(result.Conditions == 1)
                            icon.Value = Image.FromStream(
                                thisExe.GetManifestResourceStream("WeFeTeUI.icons.document.png"));
                        else
                            icon.Value = Image.FromStream(
                                thisExe.GetManifestResourceStream("WeFeTeUI.icons.cross.png"));
                        break;
                    case "Cookie":
                        if(result.Conditions == 2)
                            icon.Value = Image.FromStream(
                                thisExe.GetManifestResourceStream("WeFeTeUI.icons.cookie.png"));
                        else if(result.Conditions == 1)
                            icon.Value = Image.FromStream(
                                thisExe.GetManifestResourceStream("WeFeTeUI.icons.cookie-bite.png"));
                        else
                            icon.Value = Image.FromStream(
                                thisExe.GetManifestResourceStream("WeFeTeUI.icons.cross.png"));
                        break;
                    case "Folder":
                        if(result.Conditions == 1)
                            icon.Value = Image.FromStream(
                                thisExe.GetManifestResourceStream("WeFeTeUI.icons.folder-horizontal.png"));
                        else
                            icon.Value = Image.FromStream(
                                thisExe.GetManifestResourceStream("WeFeTeUI.icons.cross.png"));
                        break;
                    case "Header":
                        if(result.Conditions == 2)
                            icon.Value = Image.FromStream(
                                thisExe.GetManifestResourceStream("WeFeTeUI.icons.globe.png"));
                        else                    
                            icon.Value = Image.FromStream(
                                thisExe.GetManifestResourceStream("WeFeTeUI.icons.cross.png"));
                        break;
                    default:
                        icon.Value = Image.FromStream(
                            thisExe.GetManifestResourceStream("WeFeTeUI.icons.cross.png"));
                        break;
                }

                name.Value = "  " + result.ResourceName;

                // Debug!!
                //DataGridViewTextBoxCell value = new DataGridViewTextBoxCell();
                //value.Value = result.Conditions.ToString();
                //row.Cells.Add(value);
                row.Cells.Add(icon);
                row.Cells.Add(name);
                dgvResults.Rows.Add(row);
            }
            #endregion

            tssText.Text = "Finished!";
            tspProgress.Visible = false;
      
        }

        void CleanDebug()
        {
            foreach (Control control in tcMain.TabPages[1].Controls)
            {
                if (control.Name == "tbDebug")
                {
                    control.Text = "";
                }
            }
        }

        void WriteToDebug(string debugString)
        {
            foreach (Control control in tcMain.TabPages[1].Controls)
            {
                if (control.Name == "tbDebug")
                {
                    control.Text += debugString;
                }
            }
        }

        private void cbCheckAll_CheckedChanged(object sender, EventArgs e)
        {
            cbFramework.Enabled = !cbFramework.Enabled;
        }

        private void closeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void openInBrowserToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenLinkSelected();
        }

        private void dgvResults_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            OpenLinkSelected();
        }

        private void OpenLinkSelected()
        {
            string host = tbURL.Text;
            try
            {
                DataGridViewRow row = dgvResults.SelectedRows[0];
                DataGridViewImageCell tmp = (DataGridViewImageCell)row.Cells[0];
                if (tmp.Description == "File" || tmp.Description == "Folder")
                {
                    host += row.Cells[1].Value.ToString().Trim();
                }
            }
            catch (Exception exception)
            {
                host = "http://www.pentura.com/";
            }
            finally
            {
                System.Diagnostics.Process.Start(host);
            }
        }

        private void copyURLToClipboardToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string host = tbURL.Text;
            try
            {
                DataGridViewRow row = dgvResults.SelectedRows[0];
                DataGridViewImageCell tmp = (DataGridViewImageCell)row.Cells[0];
                if (tmp.Description == "File" || tmp.Description == "Folder")
                {
                    host += row.Cells[1].Value.ToString().Trim();
                }
            }
            catch (Exception exception)
            {
                host = "http://www.pentura.com/";
            }
            finally
            {
                Clipboard.Clear();
                Clipboard.SetText(host);
            }
        }
    }
}
